<?php

namespace app\admin\controller\mall\shop;

use app\admin\controller\mall\Base;
use think\Db;
use think\Exception;

/**
 * 订单结算
 *
 * @icon fa fa-circle-o
 */
class Settlement extends Base
{
    
    /**
     * Settlement模型对象
     * @var \app\common\model\mall\shop\Settlement
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\mall\shop\Settlement;
        $this->view->assign("settlementtypeList", $this->model->getSettlementtypeList());
        $this->view->assign("settlementstatusList", $this->model->getSettlementstatusList());
    }

    /**
     * 平台与商家统一结算
     */
    public function handle($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row) $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = $this->modelSceneValidate ? $name . '.edit' : $name;
                        $result = $this->validate($params,$validate);
                        if(true !== $result){
                            // 验证失败 输出错误信息
                            $this->error($result);
                        }
                    }
                    $params['settlementStatus'] = 1;
                    $params['settlementTime'] = date('Y-m-d H:i:s');
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        //增加结算资金
                        if($row->settlementMoney>0){
                            $remark = '结算订单申请【'.$row->settlementNo.'】收入订单金额¥'.$row->settlementMoney;
                            \app\common\model\mall\shop\Shop::money($row->settlementMoney,$row->shop_id,$remark);
                        }
                        //扣除佣金
                        if($row->commissionFee>0){
                            $commissionFee = $row->commissionFee;
                            //如果backMoney小于0则说明平台收到的钱不足以支付佣金，佣金为结算资金
                            if($row->backMoney<0){
                                $commissionFee = $row->settlementNo;
                            }
                            $remark = '结算订单申请【'.$row->settlementNo.'】支出订单佣金¥'.$commissionFee."。".(($row->remarks!='')?"【操作备注】：".$row->remarks:'');
                            \app\common\model\mall\shop\Shop::money(-$commissionFee,$row->shop_id,$remark);
                        }
                        Db::commit();
                        $this->success();
                    } else {
                        Db::rollback();
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        //获取结算单所包括的定单
        if ($this->request->isAjax()) {
            if(!$ids)$ids=$this->request->param("ids");
            $list = Db::name('mall_order_order')
                ->where('settlement_id',$ids)
                ->select();

            $result = array("total" => count($list), "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 结算单详情
     */
    public function detail($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row) $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $this->view->assign("row", $row);
        //获取结算单所包括的定单
        if ($this->request->isAjax()) {
            if(!$ids)$ids=$this->request->param("ids");
            $list = Db::name('mall_order_order')
                ->where('settlement_id',$ids)
                ->select();

            $result = array("total" => count($list), "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
}
